
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>LLVM Atomic Instructions and Concurrency Guide &mdash; LLVM 3.7 documentation</title>
    
    <link rel="stylesheet" href="_static/llvm-theme.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    './',
        VERSION:     '3.7',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="top" title="LLVM 3.7 documentation" href="index.html" />
    <link rel="next" title="LLVM Coding Standards" href="CodingStandards.html" />
    <link rel="prev" title="MCJIT Design and Implementation" href="MCJITDesignAndImplementation.html" />
<style type="text/css">
  table.right { float: right; margin-left: 20px; }
  table.right td { border: 1px solid #ccc; }
</style>

  </head>
  <body role="document">
<div class="logo">
  <a href="index.html">
    <img src="_static/logo.png"
         alt="LLVM Logo" width="250" height="88"/></a>
</div>

    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="CodingStandards.html" title="LLVM Coding Standards"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="MCJITDesignAndImplementation.html" title="MCJIT Design and Implementation"
             accesskey="P">previous</a> |</li>
  <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="index.html">Documentation</a>&raquo;</li>
 
      </ul>
    </div>


    <div class="document">
      <div class="documentwrapper">
          <div class="body" role="main">
            
  <div class="section" id="llvm-atomic-instructions-and-concurrency-guide">
<h1>LLVM Atomic Instructions and Concurrency Guide<a class="headerlink" href="#llvm-atomic-instructions-and-concurrency-guide" title="Permalink to this headline">¶</a></h1>
<div class="contents local topic" id="contents">
<ul class="simple">
<li><a class="reference internal" href="#introduction" id="id4">Introduction</a></li>
<li><a class="reference internal" href="#optimization-outside-atomic" id="id5">Optimization outside atomic</a></li>
<li><a class="reference internal" href="#atomic-instructions" id="id6">Atomic instructions</a></li>
<li><a class="reference internal" href="#atomic-orderings" id="id7">Atomic orderings</a><ul>
<li><a class="reference internal" href="#notatomic" id="id8">NotAtomic</a></li>
<li><a class="reference internal" href="#unordered" id="id9">Unordered</a></li>
<li><a class="reference internal" href="#monotonic" id="id10">Monotonic</a></li>
<li><a class="reference internal" href="#acquire" id="id11">Acquire</a></li>
<li><a class="reference internal" href="#release" id="id12">Release</a></li>
<li><a class="reference internal" href="#acquirerelease" id="id13">AcquireRelease</a></li>
<li><a class="reference internal" href="#sequentiallyconsistent" id="id14">SequentiallyConsistent</a></li>
</ul>
</li>
<li><a class="reference internal" href="#atomics-and-ir-optimization" id="id15">Atomics and IR optimization</a></li>
<li><a class="reference internal" href="#atomics-and-codegen" id="id16">Atomics and Codegen</a></li>
</ul>
</div>
<div class="section" id="introduction">
<h2><a class="toc-backref" href="#id4">Introduction</a><a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>Historically, LLVM has not had very strong support for concurrency; some minimal
intrinsics were provided, and <code class="docutils literal"><span class="pre">volatile</span></code> was used in some cases to achieve
rough semantics in the presence of concurrency.  However, this is changing;
there are now new instructions which are well-defined in the presence of threads
and asynchronous signals, and the model for existing instructions has been
clarified in the IR.</p>
<p>The atomic instructions are designed specifically to provide readable IR and
optimized code generation for the following:</p>
<ul class="simple">
<li>The new C++11 <code class="docutils literal"><span class="pre">&lt;atomic&gt;</span></code> header.  (<a class="reference external" href="http://www.open-std.org/jtc1/sc22/wg21/">C++11 draft available here</a>.) (<a class="reference external" href="http://www.open-std.org/jtc1/sc22/wg14/">C11 draft available here</a>.)</li>
<li>Proper semantics for Java-style memory, for both <code class="docutils literal"><span class="pre">volatile</span></code> and regular
shared variables. (<a class="reference external" href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html">Java Specification</a>)</li>
<li>gcc-compatible <code class="docutils literal"><span class="pre">__sync_*</span></code> builtins. (<a class="reference external" href="https://gcc.gnu.org/onlinedocs/gcc/_005f_005fsync-Builtins.html">Description</a>)</li>
<li>Other scenarios with atomic semantics, including <code class="docutils literal"><span class="pre">static</span></code> variables with
non-trivial constructors in C++.</li>
</ul>
<p>Atomic and volatile in the IR are orthogonal; &#8220;volatile&#8221; is the C/C++ volatile,
which ensures that every volatile load and store happens and is performed in the
stated order.  A couple examples: if a SequentiallyConsistent store is
immediately followed by another SequentiallyConsistent store to the same
address, the first store can be erased. This transformation is not allowed for a
pair of volatile stores. On the other hand, a non-volatile non-atomic load can
be moved across a volatile load freely, but not an Acquire load.</p>
<p>This document is intended to provide a guide to anyone either writing a frontend
for LLVM or working on optimization passes for LLVM with a guide for how to deal
with instructions with special semantics in the presence of concurrency.  This
is not intended to be a precise guide to the semantics; the details can get
extremely complicated and unreadable, and are not usually necessary.</p>
</div>
<div class="section" id="optimization-outside-atomic">
<span id="id1"></span><h2><a class="toc-backref" href="#id5">Optimization outside atomic</a><a class="headerlink" href="#optimization-outside-atomic" title="Permalink to this headline">¶</a></h2>
<p>The basic <code class="docutils literal"><span class="pre">'load'</span></code> and <code class="docutils literal"><span class="pre">'store'</span></code> allow a variety of optimizations, but can
lead to undefined results in a concurrent environment; see <a class="reference internal" href="#notatomic">NotAtomic</a>. This
section specifically goes into the one optimizer restriction which applies in
concurrent environments, which gets a bit more of an extended description
because any optimization dealing with stores needs to be aware of it.</p>
<p>From the optimizer&#8217;s point of view, the rule is that if there are not any
instructions with atomic ordering involved, concurrency does not matter, with
one exception: if a variable might be visible to another thread or signal
handler, a store cannot be inserted along a path where it might not execute
otherwise.  Take the following example:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="cm">/* C code, for readability; run through clang -O2 -S -emit-llvm to get</span>
<span class="cm">    equivalent IR */</span>
 <span class="kt">int</span> <span class="n">x</span><span class="p">;</span>
 <span class="kt">void</span> <span class="nf">f</span><span class="p">(</span><span class="kt">int</span><span class="o">*</span> <span class="n">a</span><span class="p">)</span> <span class="p">{</span>
   <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">100</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
     <span class="k">if</span> <span class="p">(</span><span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
       <span class="n">x</span> <span class="o">+=</span> <span class="mi">1</span><span class="p">;</span>
   <span class="p">}</span>
 <span class="p">}</span>
</pre></div>
</div>
<p>The following is equivalent in non-concurrent situations:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="kt">int</span> <span class="n">x</span><span class="p">;</span>
<span class="kt">void</span> <span class="nf">f</span><span class="p">(</span><span class="kt">int</span><span class="o">*</span> <span class="n">a</span><span class="p">)</span> <span class="p">{</span>
  <span class="kt">int</span> <span class="n">xtemp</span> <span class="o">=</span> <span class="n">x</span><span class="p">;</span>
  <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">100</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
      <span class="n">xtemp</span> <span class="o">+=</span> <span class="mi">1</span><span class="p">;</span>
  <span class="p">}</span>
  <span class="n">x</span> <span class="o">=</span> <span class="n">xtemp</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>However, LLVM is not allowed to transform the former to the latter: it could
indirectly introduce undefined behavior if another thread can access <code class="docutils literal"><span class="pre">x</span></code> at
the same time. (This example is particularly of interest because before the
concurrency model was implemented, LLVM would perform this transformation.)</p>
<p>Note that speculative loads are allowed; a load which is part of a race returns
<code class="docutils literal"><span class="pre">undef</span></code>, but does not have undefined behavior.</p>
</div>
<div class="section" id="atomic-instructions">
<h2><a class="toc-backref" href="#id6">Atomic instructions</a><a class="headerlink" href="#atomic-instructions" title="Permalink to this headline">¶</a></h2>
<p>For cases where simple loads and stores are not sufficient, LLVM provides
various atomic instructions. The exact guarantees provided depend on the
ordering; see <a class="reference internal" href="#atomic-orderings">Atomic orderings</a>.</p>
<p><code class="docutils literal"><span class="pre">load</span> <span class="pre">atomic</span></code> and <code class="docutils literal"><span class="pre">store</span> <span class="pre">atomic</span></code> provide the same basic functionality as
non-atomic loads and stores, but provide additional guarantees in situations
where threads and signals are involved.</p>
<p><code class="docutils literal"><span class="pre">cmpxchg</span></code> and <code class="docutils literal"><span class="pre">atomicrmw</span></code> are essentially like an atomic load followed by an
atomic store (where the store is conditional for <code class="docutils literal"><span class="pre">cmpxchg</span></code>), but no other
memory operation can happen on any thread between the load and store.</p>
<p>A <code class="docutils literal"><span class="pre">fence</span></code> provides Acquire and/or Release ordering which is not part of
another operation; it is normally used along with Monotonic memory operations.
A Monotonic load followed by an Acquire fence is roughly equivalent to an
Acquire load, and a Monotonic store following a Release fence is roughly
equivalent to a Release store. SequentiallyConsistent fences behave as both
an Acquire and a Release fence, and offer some additional complicated
guarantees, see the C++11 standard for details.</p>
<p>Frontends generating atomic instructions generally need to be aware of the
target to some degree; atomic instructions are guaranteed to be lock-free, and
therefore an instruction which is wider than the target natively supports can be
impossible to generate.</p>
</div>
<div class="section" id="atomic-orderings">
<span id="id2"></span><h2><a class="toc-backref" href="#id7">Atomic orderings</a><a class="headerlink" href="#atomic-orderings" title="Permalink to this headline">¶</a></h2>
<p>In order to achieve a balance between performance and necessary guarantees,
there are six levels of atomicity. They are listed in order of strength; each
level includes all the guarantees of the previous level except for
Acquire/Release. (See also <a class="reference external" href="LangRef.html#ordering">LangRef Ordering</a>.)</p>
<div class="section" id="notatomic">
<span id="id3"></span><h3><a class="toc-backref" href="#id8">NotAtomic</a><a class="headerlink" href="#notatomic" title="Permalink to this headline">¶</a></h3>
<p>NotAtomic is the obvious, a load or store which is not atomic. (This isn&#8217;t
really a level of atomicity, but is listed here for comparison.) This is
essentially a regular load or store. If there is a race on a given memory
location, loads from that location return undef.</p>
<dl class="docutils">
<dt>Relevant standard</dt>
<dd>This is intended to match shared variables in C/C++, and to be used in any
other context where memory access is necessary, and a race is impossible. (The
precise definition is in <a class="reference external" href="LangRef.html#memmodel">LangRef Memory Model</a>.)</dd>
<dt>Notes for frontends</dt>
<dd>The rule is essentially that all memory accessed with basic loads and stores
by multiple threads should be protected by a lock or other synchronization;
otherwise, you are likely to run into undefined behavior. If your frontend is
for a &#8220;safe&#8221; language like Java, use Unordered to load and store any shared
variable.  Note that NotAtomic volatile loads and stores are not properly
atomic; do not try to use them as a substitute. (Per the C/C++ standards,
volatile does provide some limited guarantees around asynchronous signals, but
atomics are generally a better solution.)</dd>
<dt>Notes for optimizers</dt>
<dd>Introducing loads to shared variables along a codepath where they would not
otherwise exist is allowed; introducing stores to shared variables is not. See
<a class="reference internal" href="#optimization-outside-atomic">Optimization outside atomic</a>.</dd>
<dt>Notes for code generation</dt>
<dd>The one interesting restriction here is that it is not allowed to write to
bytes outside of the bytes relevant to a store.  This is mostly relevant to
unaligned stores: it is not allowed in general to convert an unaligned store
into two aligned stores of the same width as the unaligned store. Backends are
also expected to generate an i8 store as an i8 store, and not an instruction
which writes to surrounding bytes.  (If you are writing a backend for an
architecture which cannot satisfy these restrictions and cares about
concurrency, please send an email to llvm-dev.)</dd>
</dl>
</div>
<div class="section" id="unordered">
<h3><a class="toc-backref" href="#id9">Unordered</a><a class="headerlink" href="#unordered" title="Permalink to this headline">¶</a></h3>
<p>Unordered is the lowest level of atomicity. It essentially guarantees that races
produce somewhat sane results instead of having undefined behavior.  It also
guarantees the operation to be lock-free, so it does not depend on the data
being part of a special atomic structure or depend on a separate per-process
global lock.  Note that code generation will fail for unsupported atomic
operations; if you need such an operation, use explicit locking.</p>
<dl class="docutils">
<dt>Relevant standard</dt>
<dd>This is intended to match the Java memory model for shared variables.</dd>
<dt>Notes for frontends</dt>
<dd>This cannot be used for synchronization, but is useful for Java and other
&#8220;safe&#8221; languages which need to guarantee that the generated code never
exhibits undefined behavior. Note that this guarantee is cheap on common
platforms for loads of a native width, but can be expensive or unavailable for
wider loads, like a 64-bit store on ARM. (A frontend for Java or other &#8220;safe&#8221;
languages would normally split a 64-bit store on ARM into two 32-bit unordered
stores.)</dd>
<dt>Notes for optimizers</dt>
<dd>In terms of the optimizer, this prohibits any transformation that transforms a
single load into multiple loads, transforms a store into multiple stores,
narrows a store, or stores a value which would not be stored otherwise.  Some
examples of unsafe optimizations are narrowing an assignment into a bitfield,
rematerializing a load, and turning loads and stores into a memcpy
call. Reordering unordered operations is safe, though, and optimizers should
take advantage of that because unordered operations are common in languages
that need them.</dd>
<dt>Notes for code generation</dt>
<dd>These operations are required to be atomic in the sense that if you use
unordered loads and unordered stores, a load cannot see a value which was
never stored.  A normal load or store instruction is usually sufficient, but
note that an unordered load or store cannot be split into multiple
instructions (or an instruction which does multiple memory operations, like
<code class="docutils literal"><span class="pre">LDRD</span></code> on ARM without LPAE, or not naturally-aligned <code class="docutils literal"><span class="pre">LDRD</span></code> on LPAE ARM).</dd>
</dl>
</div>
<div class="section" id="monotonic">
<h3><a class="toc-backref" href="#id10">Monotonic</a><a class="headerlink" href="#monotonic" title="Permalink to this headline">¶</a></h3>
<p>Monotonic is the weakest level of atomicity that can be used in synchronization
primitives, although it does not provide any general synchronization. It
essentially guarantees that if you take all the operations affecting a specific
address, a consistent ordering exists.</p>
<dl class="docutils">
<dt>Relevant standard</dt>
<dd>This corresponds to the C++11/C11 <code class="docutils literal"><span class="pre">memory_order_relaxed</span></code>; see those
standards for the exact definition.</dd>
<dt>Notes for frontends</dt>
<dd>If you are writing a frontend which uses this directly, use with caution.  The
guarantees in terms of synchronization are very weak, so make sure these are
only used in a pattern which you know is correct.  Generally, these would
either be used for atomic operations which do not protect other memory (like
an atomic counter), or along with a <code class="docutils literal"><span class="pre">fence</span></code>.</dd>
<dt>Notes for optimizers</dt>
<dd>In terms of the optimizer, this can be treated as a read+write on the relevant
memory location (and alias analysis will take advantage of that). In addition,
it is legal to reorder non-atomic and Unordered loads around Monotonic
loads. CSE/DSE and a few other optimizations are allowed, but Monotonic
operations are unlikely to be used in ways which would make those
optimizations useful.</dd>
<dt>Notes for code generation</dt>
<dd>Code generation is essentially the same as that for unordered for loads and
stores.  No fences are required.  <code class="docutils literal"><span class="pre">cmpxchg</span></code> and <code class="docutils literal"><span class="pre">atomicrmw</span></code> are required
to appear as a single operation.</dd>
</dl>
</div>
<div class="section" id="acquire">
<h3><a class="toc-backref" href="#id11">Acquire</a><a class="headerlink" href="#acquire" title="Permalink to this headline">¶</a></h3>
<p>Acquire provides a barrier of the sort necessary to acquire a lock to access
other memory with normal loads and stores.</p>
<dl class="docutils">
<dt>Relevant standard</dt>
<dd>This corresponds to the C++11/C11 <code class="docutils literal"><span class="pre">memory_order_acquire</span></code>. It should also be
used for C++11/C11 <code class="docutils literal"><span class="pre">memory_order_consume</span></code>.</dd>
<dt>Notes for frontends</dt>
<dd>If you are writing a frontend which uses this directly, use with caution.
Acquire only provides a semantic guarantee when paired with a Release
operation.</dd>
<dt>Notes for optimizers</dt>
<dd>Optimizers not aware of atomics can treat this like a nothrow call.  It is
also possible to move stores from before an Acquire load or read-modify-write
operation to after it, and move non-Acquire loads from before an Acquire
operation to after it.</dd>
<dt>Notes for code generation</dt>
<dd>Architectures with weak memory ordering (essentially everything relevant today
except x86 and SPARC) require some sort of fence to maintain the Acquire
semantics.  The precise fences required varies widely by architecture, but for
a simple implementation, most architectures provide a barrier which is strong
enough for everything (<code class="docutils literal"><span class="pre">dmb</span></code> on ARM, <code class="docutils literal"><span class="pre">sync</span></code> on PowerPC, etc.).  Putting
such a fence after the equivalent Monotonic operation is sufficient to
maintain Acquire semantics for a memory operation.</dd>
</dl>
</div>
<div class="section" id="release">
<h3><a class="toc-backref" href="#id12">Release</a><a class="headerlink" href="#release" title="Permalink to this headline">¶</a></h3>
<p>Release is similar to Acquire, but with a barrier of the sort necessary to
release a lock.</p>
<dl class="docutils">
<dt>Relevant standard</dt>
<dd>This corresponds to the C++11/C11 <code class="docutils literal"><span class="pre">memory_order_release</span></code>.</dd>
<dt>Notes for frontends</dt>
<dd>If you are writing a frontend which uses this directly, use with caution.
Release only provides a semantic guarantee when paired with a Acquire
operation.</dd>
<dt>Notes for optimizers</dt>
<dd>Optimizers not aware of atomics can treat this like a nothrow call.  It is
also possible to move loads from after a Release store or read-modify-write
operation to before it, and move non-Release stores from after an Release
operation to before it.</dd>
<dt>Notes for code generation</dt>
<dd>See the section on Acquire; a fence before the relevant operation is usually
sufficient for Release. Note that a store-store fence is not sufficient to
implement Release semantics; store-store fences are generally not exposed to
IR because they are extremely difficult to use correctly.</dd>
</dl>
</div>
<div class="section" id="acquirerelease">
<h3><a class="toc-backref" href="#id13">AcquireRelease</a><a class="headerlink" href="#acquirerelease" title="Permalink to this headline">¶</a></h3>
<p>AcquireRelease (<code class="docutils literal"><span class="pre">acq_rel</span></code> in IR) provides both an Acquire and a Release
barrier (for fences and operations which both read and write memory).</p>
<dl class="docutils">
<dt>Relevant standard</dt>
<dd>This corresponds to the C++11/C11 <code class="docutils literal"><span class="pre">memory_order_acq_rel</span></code>.</dd>
<dt>Notes for frontends</dt>
<dd>If you are writing a frontend which uses this directly, use with caution.
Acquire only provides a semantic guarantee when paired with a Release
operation, and vice versa.</dd>
<dt>Notes for optimizers</dt>
<dd>In general, optimizers should treat this like a nothrow call; the possible
optimizations are usually not interesting.</dd>
<dt>Notes for code generation</dt>
<dd>This operation has Acquire and Release semantics; see the sections on Acquire
and Release.</dd>
</dl>
</div>
<div class="section" id="sequentiallyconsistent">
<h3><a class="toc-backref" href="#id14">SequentiallyConsistent</a><a class="headerlink" href="#sequentiallyconsistent" title="Permalink to this headline">¶</a></h3>
<p>SequentiallyConsistent (<code class="docutils literal"><span class="pre">seq_cst</span></code> in IR) provides Acquire semantics for loads
and Release semantics for stores. Additionally, it guarantees that a total
ordering exists between all SequentiallyConsistent operations.</p>
<dl class="docutils">
<dt>Relevant standard</dt>
<dd>This corresponds to the C++11/C11 <code class="docutils literal"><span class="pre">memory_order_seq_cst</span></code>, Java volatile, and
the gcc-compatible <code class="docutils literal"><span class="pre">__sync_*</span></code> builtins which do not specify otherwise.</dd>
<dt>Notes for frontends</dt>
<dd>If a frontend is exposing atomic operations, these are much easier to reason
about for the programmer than other kinds of operations, and using them is
generally a practical performance tradeoff.</dd>
<dt>Notes for optimizers</dt>
<dd>Optimizers not aware of atomics can treat this like a nothrow call.  For
SequentiallyConsistent loads and stores, the same reorderings are allowed as
for Acquire loads and Release stores, except that SequentiallyConsistent
operations may not be reordered.</dd>
<dt>Notes for code generation</dt>
<dd>SequentiallyConsistent loads minimally require the same barriers as Acquire
operations and SequentiallyConsistent stores require Release
barriers. Additionally, the code generator must enforce ordering between
SequentiallyConsistent stores followed by SequentiallyConsistent loads. This
is usually done by emitting either a full fence before the loads or a full
fence after the stores; which is preferred varies by architecture.</dd>
</dl>
</div>
</div>
<div class="section" id="atomics-and-ir-optimization">
<h2><a class="toc-backref" href="#id15">Atomics and IR optimization</a><a class="headerlink" href="#atomics-and-ir-optimization" title="Permalink to this headline">¶</a></h2>
<p>Predicates for optimizer writers to query:</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">isSimple()</span></code>: A load or store which is not volatile or atomic.  This is
what, for example, memcpyopt would check for operations it might transform.</li>
<li><code class="docutils literal"><span class="pre">isUnordered()</span></code>: A load or store which is not volatile and at most
Unordered. This would be checked, for example, by LICM before hoisting an
operation.</li>
<li><code class="docutils literal"><span class="pre">mayReadFromMemory()</span></code>/<code class="docutils literal"><span class="pre">mayWriteToMemory()</span></code>: Existing predicate, but note
that they return true for any operation which is volatile or at least
Monotonic.</li>
<li><code class="docutils literal"><span class="pre">isAtLeastAcquire()</span></code>/<code class="docutils literal"><span class="pre">isAtLeastRelease()</span></code>: These are predicates on
orderings. They can be useful for passes that are aware of atomics, for
example to do DSE across a single atomic access, but not across a
release-acquire pair (see MemoryDependencyAnalysis for an example of this)</li>
<li>Alias analysis: Note that AA will return ModRef for anything Acquire or
Release, and for the address accessed by any Monotonic operation.</li>
</ul>
<p>To support optimizing around atomic operations, make sure you are using the
right predicates; everything should work if that is done.  If your pass should
optimize some atomic operations (Unordered operations in particular), make sure
it doesn&#8217;t replace an atomic load or store with a non-atomic operation.</p>
<p>Some examples of how optimizations interact with various kinds of atomic
operations:</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">memcpyopt</span></code>: An atomic operation cannot be optimized into part of a
memcpy/memset, including unordered loads/stores.  It can pull operations
across some atomic operations.</li>
<li>LICM: Unordered loads/stores can be moved out of a loop.  It just treats
monotonic operations like a read+write to a memory location, and anything
stricter than that like a nothrow call.</li>
<li>DSE: Unordered stores can be DSE&#8217;ed like normal stores.  Monotonic stores can
be DSE&#8217;ed in some cases, but it&#8217;s tricky to reason about, and not especially
important. It is possible in some case for DSE to operate across a stronger
atomic operation, but it is fairly tricky. DSE delegates this reasoning to
MemoryDependencyAnalysis (which is also used by other passes like GVN).</li>
<li>Folding a load: Any atomic load from a constant global can be constant-folded,
because it cannot be observed.  Similar reasoning allows scalarrepl with
atomic loads and stores.</li>
</ul>
</div>
<div class="section" id="atomics-and-codegen">
<h2><a class="toc-backref" href="#id16">Atomics and Codegen</a><a class="headerlink" href="#atomics-and-codegen" title="Permalink to this headline">¶</a></h2>
<p>Atomic operations are represented in the SelectionDAG with <code class="docutils literal"><span class="pre">ATOMIC_*</span></code> opcodes.
On architectures which use barrier instructions for all atomic ordering (like
ARM), appropriate fences can be emitted by the AtomicExpand Codegen pass if
<code class="docutils literal"><span class="pre">setInsertFencesForAtomic()</span></code> was used.</p>
<p>The MachineMemOperand for all atomic operations is currently marked as volatile;
this is not correct in the IR sense of volatile, but CodeGen handles anything
marked volatile very conservatively.  This should get fixed at some point.</p>
<p>Common architectures have some way of representing at least a pointer-sized
lock-free <code class="docutils literal"><span class="pre">cmpxchg</span></code>; such an operation can be used to implement all the other
atomic operations which can be represented in IR up to that size.  Backends are
expected to implement all those operations, but not operations which cannot be
implemented in a lock-free manner.  It is expected that backends will give an
error when given an operation which cannot be implemented.  (The LLVM code
generator is not very helpful here at the moment, but hopefully that will
change.)</p>
<p>On x86, all atomic loads generate a <code class="docutils literal"><span class="pre">MOV</span></code>. SequentiallyConsistent stores
generate an <code class="docutils literal"><span class="pre">XCHG</span></code>, other stores generate a <code class="docutils literal"><span class="pre">MOV</span></code>. SequentiallyConsistent
fences generate an <code class="docutils literal"><span class="pre">MFENCE</span></code>, other fences do not cause any code to be
generated.  cmpxchg uses the <code class="docutils literal"><span class="pre">LOCK</span> <span class="pre">CMPXCHG</span></code> instruction.  <code class="docutils literal"><span class="pre">atomicrmw</span> <span class="pre">xchg</span></code>
uses <code class="docutils literal"><span class="pre">XCHG</span></code>, <code class="docutils literal"><span class="pre">atomicrmw</span> <span class="pre">add</span></code> and <code class="docutils literal"><span class="pre">atomicrmw</span> <span class="pre">sub</span></code> use <code class="docutils literal"><span class="pre">XADD</span></code>, and all
other <code class="docutils literal"><span class="pre">atomicrmw</span></code> operations generate a loop with <code class="docutils literal"><span class="pre">LOCK</span> <span class="pre">CMPXCHG</span></code>.  Depending
on the users of the result, some <code class="docutils literal"><span class="pre">atomicrmw</span></code> operations can be translated into
operations like <code class="docutils literal"><span class="pre">LOCK</span> <span class="pre">AND</span></code>, but that does not work in general.</p>
<p>On ARM (before v8), MIPS, and many other RISC architectures, Acquire, Release,
and SequentiallyConsistent semantics require barrier instructions for every such
operation. Loads and stores generate normal instructions.  <code class="docutils literal"><span class="pre">cmpxchg</span></code> and
<code class="docutils literal"><span class="pre">atomicrmw</span></code> can be represented using a loop with LL/SC-style instructions
which take some sort of exclusive lock on a cache line (<code class="docutils literal"><span class="pre">LDREX</span></code> and <code class="docutils literal"><span class="pre">STREX</span></code>
on ARM, etc.).</p>
<p>It is often easiest for backends to use AtomicExpandPass to lower some of the
atomic constructs. Here are some lowerings it can do:</p>
<ul class="simple">
<li>cmpxchg -&gt; loop with load-linked/store-conditional
by overriding <code class="docutils literal"><span class="pre">hasLoadLinkedStoreConditional()</span></code>, <code class="docutils literal"><span class="pre">emitLoadLinked()</span></code>,
<code class="docutils literal"><span class="pre">emitStoreConditional()</span></code></li>
<li>large loads/stores -&gt; ll-sc/cmpxchg
by overriding <code class="docutils literal"><span class="pre">shouldExpandAtomicStoreInIR()</span></code>/<code class="docutils literal"><span class="pre">shouldExpandAtomicLoadInIR()</span></code></li>
<li>strong atomic accesses -&gt; monotonic accesses + fences
by using <code class="docutils literal"><span class="pre">setInsertFencesForAtomic()</span></code> and overriding <code class="docutils literal"><span class="pre">emitLeadingFence()</span></code>
and <code class="docutils literal"><span class="pre">emitTrailingFence()</span></code></li>
<li>atomic rmw -&gt; loop with cmpxchg or load-linked/store-conditional
by overriding <code class="docutils literal"><span class="pre">expandAtomicRMWInIR()</span></code></li>
</ul>
<p>For an example of all of these, look at the ARM backend.</p>
</div>
</div>


          </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="CodingStandards.html" title="LLVM Coding Standards"
             >next</a> |</li>
        <li class="right" >
          <a href="MCJITDesignAndImplementation.html" title="MCJIT Design and Implementation"
             >previous</a> |</li>
  <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="index.html">Documentation</a>&raquo;</li>
 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &copy; Copyright 2003-2015, LLVM Project.
      Last updated on 2015-09-08.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.3.1.
    </div>
  </body>
</html>